學習筆記 Go
Go的語言優勢或特性
- Produces code that runs fast and uses very little memory.
- Run across many platforms.
- Provides simple syntax for multi-threaded programs.
- Provides some object-oriented features.
- Has garbage collection.
一、Go introduction
- Go compiler, three commends(go run xxx.go, go build xxx.go, go doc )
- how to execute the file (./[file name] )(如果有加路徑在PATH就可以直接呼叫file name)
- package declaration (兩個file宣告為同一個package時,需要先經過編譯,go build main.go
- second_file.go, 執行檔才可以運作,無法直接go run)
- import package (single or multiple, and can use Alias)
二、Go Variable
- literals(俗稱字面值,例如“string”, 1, 1.567程式直接寫的數值,具體是什麼可以參考cpp road老師的youtube,會跟編譯時使用的記憶體有關)
- constants (also can be used to make enum in Go)
- basic type: int, float32, string...
- string 可以用`符號框住多行字串
- assign a variable(var [variableName] [type])
- inferred type ([variableName := [value], 不寫型別編譯器或IDE自行根據後面的初始值推斷型別)
- 基本型別的預設值為0或空字串
- operators 參考 https://www.tutorialspoint.com/go/go_operators.htm
三、Go fmt package
default type for %v
bool: %t
int, int8 etc.: %d
uint, uint8 etc.: %d, %#x if printed with %#v
float32, complex64, etc: %g
string: %s
chan: %p
pointer: %p
- fmt.Println("會自動帶空格分隔","在兩段之間以及換行")
- fmt.Print("需要自己換行\n")
- fmt.Printf("插入變數用 佔位符 %v", 9453)
- Sprint, Sprintln, Sprintf與前述一樣組字功能,但不會print而是return新組好的字串
- fmt.Scan() 需要命一個變數並且用&把變數地址進去(reference?)
- fmt.Scan() 只儲存到空格為止的第一個字,如果需要多幾個字就要多執行幾次或換其他方法
四、Go Conditionals
- if ... else if ... else
- switch case
- time package(use time.Now().UnixNano() get epoch time)
- math/rand (used to generate a random number, but need to use different seed value, such as rand.Seed(time.Now().UnixNano()) )
- 某些情況可以在if後面宣告新變數並用來進行判斷(if newValue := x*y;newValue >1000{})
記得使用package的公開函式是大寫開頭